package com.rankeiot.platform.controller;


import com.rankeiot.core.data.response.PageResp;
import com.rankeiot.core.util.StringUtil;
import com.rankeiot.platform.PlatformMenu;
import com.rankeiot.platform.domain.MultiDictionary;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;

import com.rankeiot.core.anno.Auth;
import com.rankeiot.core.inner.argumet.QueryPage;
import org.sagacity.sqltoy.dao.LightDao;
import org.sagacity.sqltoy.model.Page;
import com.rankeiot.core.data.response.Resp;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.rankeiot.core.sqltoy.Sql;


import java.util.ArrayList;
import java.util.List;

import static com.rankeiot.core.util.LocaleUtil.t;
/**
 * 多级字典
 */
@Tag(name = "多级字典")
@Auth
@RestController
@RequestMapping("multiDictionary")
@RequiredArgsConstructor
public class MultiDictionaryController {

    final LightDao dao;

    /**
     * 新增多级字典
     */
    @Operation(summary="新增多级字典")
    @Auth(PlatformMenu.MULTIDICTIONARY_ADD)
    @PostMapping("addMulti")
    @Transactional
    public Resp addMulti(@Valid @RequestBody MultiDictionary multiDictionary) {
        if(StringUtil.isEmpty(multiDictionary.getName())){
            Resp.fail(t("字典项不能为空","dictionary name cannot be empty"));
        }
        String pSn = multiDictionary.getParentSn();
        if (StringUtil.isEmpty(pSn)) {
            pSn = null;
        }
        String[] names=multiDictionary.getName().split("\n");
        String sn = dao.query().sql("select max(sn) from t_multi_dictionary where parent_sn=?")
                .values(pSn)
                .getValue(String.class);
        List<MultiDictionary> dicts=new ArrayList<>();
        long startId=0;

        int snLength = 0;
        if(sn==null){
            String strId =pSn+"01";
            if(pSn==null){
                strId="01";
            }else if(pSn.length()%2!=0){
                Resp.fail(t("编码格式错误","serial number encoding format error"));
            }

            startId=Long.valueOf(strId,36);
            snLength=strId.length();
        }else{
            startId = Long.valueOf(sn, 36) + 1;
            snLength=sn.length();
        }

        for(String name:names){
            MultiDictionary dict=new MultiDictionary();
            String dictSn = StringUtil.leftPad(Long.toString(startId, 36), '0', snLength);
            dict.setSn(dictSn);
            dict.setParentSn(pSn);
            dict.setRank(snLength/2);
            dict.setName(name);
            dicts.add(dict);
            startId++;
        }
        dao.saveAll(dicts);
//        dao.executeSql("""
//               UPDATE t_multi_dictionary t
//               JOIN (
//                   SELECT parent_sn, COUNT(*) as cnt
//                   FROM t_multi_dictionary
//               		WHERE parent_sn =?
//                   GROUP BY parent_sn
//               ) s ON t.sn = s.parent_sn
//               SET t.sub_count = s.cnt
//                WHERE sn = ?
//               ;
//               """,pSn,pSn);
        return Resp.ok();
    }
    /**
     * 新增多级字典
     */
    @Operation(summary="新增多级字典")
    @Auth(PlatformMenu.MULTIDICTIONARY_ADD)
    @PostMapping("add")
    @Transactional
    public Resp add(@Valid @RequestBody MultiDictionary multiDictionary) {
        String pSn = multiDictionary.getParentSn();
        if (StringUtil.isEmpty(pSn)) {
            pSn = null;
            multiDictionary.setParentSn(null);
        }
        String sn = dao.query().sql("select max(sn) from t_multi_dictionary where parent_sn=?")
                .values(pSn)
                .getValue(String.class);
        if(sn==null){
            String strId =pSn+"01";
            if(pSn==null){
                strId="01";
            }else if(pSn.length()%2!=0){
                Resp.fail(t("编码格式错误","serial number encoding format error"));
            }
            multiDictionary.setSn(strId);
            multiDictionary.setParentSn(pSn);
            multiDictionary.setRank(strId.length()/2);
        }else{
            int length = sn.length();
            long id = Long.valueOf(sn, 36) + 1;
            String strId = StringUtil.leftPad(Long.toString(id, 36), '0', length);
            multiDictionary.setSn(strId);
            multiDictionary.setRank(1);
        }
        dao.save(multiDictionary);
//       dao.executeSql("""
//               UPDATE t_multi_dictionary t
//               JOIN (
//                   SELECT parent_sn, COUNT(*) as cnt
//                   FROM t_multi_dictionary
//               		WHERE parent_sn =?
//                   GROUP BY parent_sn
//               ) s ON t.sn = s.parent_sn
//               SET t.sub_count = s.cnt
//                WHERE sn = ?
//               ;
//               """,pSn,pSn);
        return Resp.ok();
    }

    /**
     * 删除多级字典
     */
    @Operation(summary="删除多级字典")
    @Auth(PlatformMenu.MULTIDICTIONARY_DELETE)
    @Transactional
    @PostMapping("delete")
    public Resp delete(List<String> sns) {
        // dao.loadAll(multiDictionarys);
//        List<MultiDictionary> multiDictionarys = CollectionUtil.map(sns, MultiDictionary::new);
//        dao.deleteAll(multiDictionarys);
        for (String sn : sns) {
            dao.execute()
                    .autoCommit(false)
                    .sql("delete from t_multi_dictionary where sn like ?")
                    .values(sn + "%")
                    .submit();
        }
        //更新子节点数
//        dao.executeSql("""
//            UPDATE t_multi_dictionary t
//            JOIN (
//                SELECT parent_sn, COUNT(*) as cnt
//                FROM t_multi_dictionary
//                GROUP BY parent_sn
//            ) s ON t.sn = s.parent_sn
//            SET t.sub_count = s.cnt
//        """);
        return Resp.ok();
    }

    /**
     * 更新多级字典
     */
    @Operation(summary="更新多级字典")
    @Auth(PlatformMenu.MULTIDICTIONARY_EDIT)
    @PostMapping("save")
    public Resp save(@Valid @RequestBody MultiDictionary multiDictionary) {
        dao.update(multiDictionary);
        return Resp.ok();
    }

    /**
     * 获取多级字典
     */
    @Operation(summary="获取多级字典详细")
    @Auth(PlatformMenu.MULTIDICTIONARY)
    @GetMapping("detail")
    public Resp<MultiDictionary> detail(String sn) {
        MultiDictionary multiDictionary = dao.load(new MultiDictionary(sn));
        return Resp.of(multiDictionary);
    }

    /**
     * 获取多级字典列表
     */
    @Operation(summary="列出多级字典")
    @Auth(PlatformMenu.MULTIDICTIONARY)
    @PostMapping("list")
    public PageResp<MultiDictionary> list(QueryPage query) {
        String sql = Sql.select("sn,name,code,icon")
                .from(MultiDictionary.TABLE)
                .optional(q -> q
                        .like(MultiDictionary.Fields.sn)
                        .eq(MultiDictionary.Fields.parentSn)
                        .eq(MultiDictionary.Fields.name)
                        .eq(MultiDictionary.Fields.rank)
                ).orderBy(MultiDictionary.Fields.sn.name())
                .toString();
        Page result = dao.findPage(query.page(), sql, query.params(), MultiDictionary.class);
        return Resp.of(result);
    }

}
